package com.tongguan.paypos.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import com.basewin.services.ServiceManager;
import com.tencent.bugly.crashreport.CrashReport;
import com.tongguan.paypos.R;
import com.tongguan.paypos.base.BaseActivity;
import com.tongguan.paypos.base.MyApplication;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.UrlConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.db.UserDao;
import com.tongguan.paypos.entity.MerchantKeyInfo;
import com.tongguan.paypos.entity.PayType;
import com.tongguan.paypos.entity.PayTypeInfo;
import com.tongguan.paypos.entity.UserInfo;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.utils.CipherUtils;
import com.tongguan.paypos.utils.SPUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.view.DropDownEditText;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_user_name)
    DropDownEditText mEtUserName;
    @BindView(R.id.et_user_pwd)
    EditText mEtUserPwd;
    @BindView(R.id.chk_remember)
    CheckBox mChkRemember;
    @BindView(R.id.btn_login)
    Button mBtnLogin;
    @BindView(R.id.iv_dropDown)
    ImageView mIvDropDown;

    private ArrayList<UserInfo> accounts;
    private ArrayList<String> data;
    private String account;
    private String password;
    private String posId;//="N9NL10087290";
    // private boolean needCallback; //跳转到那个activity 暂时不用
    private int connectType;//网络连接状态 （）
    private boolean isDownloadKey;//是否签名

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
//      needCallback = getIntent().getBooleanExtra(AppConstants.NEEDCALLBACK,false);
        ButterKnife.bind(this);
        connectType = (int) SPUtils.getSp(context, AppConstants.NET_CONNECT_TYPE, 0);
        isDownloadKey = (boolean) SPUtils.getSp(context, AppConstants.DOWNLOAD_KEY, false);
        initSN();
        initEvent();
    }

    private void initSN() {
        posId = (String) SPUtils.getSp(context, AppConstants.DEVICE_SN, "");
        if (TextUtils.isEmpty(posId)) {
            try {
                posId = ServiceManager.getInstence().getDeviceinfo().getSN();
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showCustom(context,"SN获取失败");
                return;
            }
            SPUtils.setSP(context, AppConstants.DEVICE_SN, posId);
            L.d("初始化posId " + posId);
        }
    }

    private void initEvent() {
        String defAccount = (String) SPUtils.getSp(context, AppConstants.LOGIN_NAME, "");
        String defPassword = (String) SPUtils.getSp(context, AppConstants.LOGIN_PWD, "");
        mEtUserName.setText(defAccount);
        mEtUserPwd.setText(defPassword);
        boolean isRemember = (boolean) SPUtils.getSp(context, AppConstants.REMEMBER, true);
        mChkRemember.setChecked(isRemember);
        accounts = UserDao.getAccountList(this);
        data = new ArrayList<>();
        for (int i = 0; i < accounts.size(); i++) {
            data.add(accounts.get(i).getAccount());
        }
        mIvDropDown.setOnClickListener(v -> {
            try {
                if (accounts == null || accounts.size() == 0) {
                    return;
                }
                mEtUserName.setShowData(data);
                mEtUserName.setOnClick();
            } catch (Exception e) {
                e.printStackTrace();
                L.d("登录历史记录异常");
            }
        });
        mEtUserName.setOnPopItemClickListener(index -> mEtUserPwd.setText(accounts.get(index).getPassword()));
        mBtnLogin.setOnClickListener(v -> login());
    }

    private void login() {
        account = mEtUserName.getText().toString();
        password = mEtUserPwd.getText().toString();

        if (TextUtils.isEmpty(account)) {
            ToastUtils.showCustom(context, R.string.toast_login_name);
            return;
        }

        if (TextUtils.isEmpty(password)) {
            ToastUtils.showCustom(context, R.string.toast_login_pwd);
            return;
        }

        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, account);
        params.put(UrlConstants.KEY_POS_ID, posId);
        params.put(UrlConstants.KEY_PASSWORD, CipherUtils.md5(password));
        RequestCallback.post(context, UrlConstants.LOGIN_URL + account, params, mDialog, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                UserInfo userInfo = UserInfo.objectFromData(response);
                if (userInfo.getStatus() != 100) {
                    ToastUtils.showCustom(context, userInfo.getMessage());
                    return;
                }
                //是否下载过数字签名key
//                if (isDownloadKey){
                    process(userInfo);
//                }else {
//                    downloadKey(userInfo);
//                }
            }
        });
    }

    /**
     * 下载密钥
     */
    private void downloadKey(UserInfo userInfo) {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT,account);
        params.put(UrlConstants.KEY_POS_ID,posId);
        RequestCallback.post(context, UrlConstants.MERCHANT_KEY, params, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                MerchantKeyInfo info = MerchantKeyInfo.objectFromData(response);
                if (info.getStatus()!=100){
                    ToastUtils.showCustom(context,info.getMessage());
                    return;
                }
                SPUtils.setSP(context,AppConstants.SIGNATURE,info.getMerchantKey());
                SPUtils.setSP(context,AppConstants.DOWNLOAD_KEY,true);
                process(userInfo);
            }
        });
    }

    private void process(UserInfo userInfo){
        User user = User.getInstance();
        user.reset();
        user.setAccount(account);
        user.setMerchantName(userInfo.getMerchantName());
        user.setMerchantId(userInfo.getMerchantId());
        user.setWxMerchantName(userInfo.getWxMerchantName());
        user.setWxMerchantId(userInfo.getWxMerchantId());
        user.setZfbMerchantName(userInfo.getZfbMerchantName());
        user.setZfbMerchantId(userInfo.getZfbMerchantId());
        user.setPosId(posId);
        user.setLoginStatus(true);
        User.getInstance().setNetConnectType(connectType);//再次保存
        user.save();
        //if (needCallback)
        //是否记住密码 取消后连同数据库的一起删掉
        if (mChkRemember.isChecked()) {
            UserDao.addAccount(context, account, password);
            SPUtils.setSP(context, AppConstants.REMEMBER, true);
            SPUtils.setSP(context, AppConstants.LOGIN_NAME, account);//登录默认显示的用户
            SPUtils.setSP(context, AppConstants.LOGIN_PWD, password);//登录默认密码
        } else {
            UserDao.delAccount(context, account);
            SPUtils.setSP(context, AppConstants.REMEMBER, false);
            SPUtils.setSP(context, AppConstants.LOGIN_NAME, "");//登录默认显示的用户
            SPUtils.setSP(context, AppConstants.LOGIN_PWD, "");//
        }
        initPayType();
        initCrash();
        finish();
    }

    private void initCrash() {
//        boolean crash = (boolean) SPUtils.getSp(context, AppConstants.CRASH, false);
//        if (!crash) {
        //修改bug收集机制，每天登录，进行统计
        CrashReport.setUserId(User.getInstance().getAccount());//设置ID 手机
        CrashReport.putUserData(context, "account", User.getInstance().getAccount());//设置ID 手机
        CrashReport.putUserData(context, "name", User.getInstance().getMerchantName());
        CrashReport.putUserData(context, "id", User.getInstance().getMerchantId());
        CrashReport.putUserData(context, "sn", User.getInstance().getPosId());
//            SPUtils.setSP(context, AppConstants.CRASH, true);
//        }
    }

    /**
     * 加载支付方式 每天登录必须获取
     */
    private void initPayType() {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        RequestCallback.post(context, UrlConstants.GET_PAY_TYPE, params, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayTypeInfo payTypeInfo = PayTypeInfo.objectFromData(response);
                if (payTypeInfo.getStatus() != 100) {
                    ToastUtils.showCustom(context, payTypeInfo.getMessage());
                    return;
                }
                List<PayTypeInfo.PayTypesBean> payTypes = payTypeInfo.getPayTypes();
                if (payTypes == null || payTypes.size() == 0) {
                    return;
                }
                ArrayList<PayType> mPayTypes = new ArrayList<>();
                //固定支付方式
                for (PayTypeInfo.PayTypesBean payType : payTypes) {
                    PayType data = AppConstants.payTypeMap.get(payType.getType());
                    if (data == null){
                        continue;
                    }
                    mPayTypes.add(data);
                }
                if (mPayTypes.size() == 0) {
                    L.d("支付方式不在本地中");
                    return;
                }
                MyApplication.getInstance().setPayTypes(mPayTypes);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RequestCallback.cancelAllRequest();
    }
}
